<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace Workerman\Protocols;

use Workerman\Connection\TcpConnection;

/**
 * Frame Protocol.
 */
class Xieyi
{

    public static function input($buffer, TcpConnection $connection)
    {

        if($connection->stage==0){

            if (strlen($buffer) < 4) {
                return 0;
            }

            $entype=substr($buffer,0,2);

            $unpack_data = unpack('nentype', $entype);

            $connection->entype=$unpack_data['entype'];

            $len=substr($buffer,2);

            $unpack_data = unpack('ntotal_length', $len);

            $connection->len=$unpack_data['total_length'];

            return $unpack_data['total_length']+4;

        }

        if($connection->stage==1){
            if (strlen($buffer) < 4) {
                return 0;
            }
            $unpack_data = unpack('Ntotal_length', $buffer);

            $connection->len=$unpack_data['total_length'];

            return $unpack_data['total_length']+4;
        }

    }


    public static function decode($buffer)
    {

        return substr($buffer, 4);
    }


    public static function encode($buffer,TcpConnection $connection)
    {
        $total_length = strlen($buffer);

        if($connection->header_len_type==0){

            //echo "不含4字节长度-->返回数据包长度-->".$total_length."\r\n";

            return $buffer;

        }else{

            //echo "返回数据包长度-->".$total_length."\r\n";

            return pack('N', $total_length). $buffer;

        }


    }
}
